<!-- 产品分类 -->
<template>
  <div class="product-category">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加分类的按钮 -->
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="openAddCategory"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- default-expand-all:是否展开所有的节点
      sortable:排序
       -->
      <el-table
        :data="categoryDatas.data"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="序号" sortable width="180">
        </el-table-column>
        <el-table-column prop="title" label="标题" sortable width="180">
        </el-table-column>
        <el-table-column prop="img" label="缩略图" sortable width="200">
          <template slot-scope="scope">
            <img :src="Setting.baseUrl + scope.row.img" alt="" width="50" />
          </template>
        </el-table-column>
        <el-table-column prop="is_show" label="是否可用" width="150">
          <!-- 每一条数据的值可以通过scope拿到 -->
          <!-- 1:可用 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_show"
              active-value="1"
              inactive-value="0"
              active-text="可"
              inactive-text="否"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              @click="handleDeleteClick(scope.row)"
              type="danger"
              size="small"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleEditClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="categoryDatas.count"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="dialogAddFormVisible">
      <el-form :model="cateDatas">
        <el-form-item label="分类选择" label-width="80px">
          <!-- 级联 
           @change:来监听得到改变的值
          -->
          <el-cascader
            v-model="value"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="changeCascader(value)"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="标题" prop="title" label-width="80px">
          <el-input v-model="cateDatas.title" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 图片 -->
        <el-form-item label="分类图片" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl + '/upload/img'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="Setting.baseUrl + imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-switch
            v-model="cateDatas.is_show"
            active-value="1"
            inactive-value="0"
            active-text="可"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddCategory">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑分类的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="dialogEditFormVisible">
      <el-form :model="editDatas">
        <el-form-item label="分类选择" label-width="80px">
          <!-- 级联 
           @change:来监听得到改变的值
          -->
          <el-cascader
            v-model="editValue"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="changeEditCascader(editValue)"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="标题" prop="title" label-width="80px">
          <el-input v-model="editDatas.title" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 图片 -->
        <el-form-item label="分类图片" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl + '/upload/img'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="Setting.baseUrl + imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-switch
            v-model="editDatas.is_show"
            active-value="1"
            inactive-value="0"
            active-text="可"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Setting from "@/utils/setting.js";
import {
  categoryDeleApi,
  categoryAddApi,
  categoryEditApi,
} from "@/api/product.js";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      page: 1,
      size: 5,
      Setting: Setting,
      currentPage: 1,
      dialogAddFormVisible: false,
      cateDatas: {
        title: "",
        img: "",
        is_show: "1",
      },
      value: [],
      imageUrl: "",
      editDatas: {
        title: "",
        img: "",
        is_show: "1",
      },
      editValue: [],
      dialogEditFormVisible: false,
    };
  },
  //计算属性 类似于data概念
  computed: {
    categoryDatas() {
      console.log(this.$store.state.product.categoryListDatas);
      return this.$store.state.product.categoryListDatas;
    },
    options() {
      console.log(this.$store.state.product.AddCategoryListDatas);
      return this.$store.state.product.AddCategoryListDatas;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getCategoryListDatas() {
      this.$store.dispatch("actChangeCategoryListDatas", {
        page: this.page,
        size: this.size,
      });
    },
    getAddCategoryListDatas() {
      this.$store.dispatch("actChangeAddCategoryListDatas");
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.getCategoryListDatas();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getCategoryListDatas();
    },
    // 删除
    handleDeleteClick(rowData) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          categoryDeleApi(rowData).then((res) => {
            console.log(res);
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getCategoryListDatas();
            } else {
              this.$message(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    openAddCategory() {
      this.dialogAddFormVisible = true;
    },
    // 头像图片上传成功的处理
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.imageUrl = res.data.name;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 头像上传之前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 提交
    submitAddCategory() {
      this.$set(this.cateDatas, "img", this.imageUrl);
      this.$set(this.cateDatas, "pid", this.value.pop());
      // 添加提交
      categoryAddApi(this.cateDatas).then((rel) => {
        this.getCategoryListDatas();
        this.dialogAddFormVisible = false;
        alert(rel.data.msg);
      });
    },
    // 当级联改变时
    changeCascader(value) {
      console.log(value);
      this.value = value;
    },
    handleEditClick(rowData) {
      // 每次调用编辑窗口,然后清空选择
      this.editValue = [];
      this.imageUrl = rowData.img;
      this.editDatas = rowData;
      this.dialogEditFormVisible = true;
    },
    // 当级编辑联改变时
    changeEditCascader(value) {
      this.editValue = value;
      console.log(this.editValue);
    },
    submitEditCategory() {
      this.$set(this.editDatas, "img", this.imageUrl);
      this.$set(this.editDatas, "pid", this.editValue.pop());
      console.log(this.editDatas);
      categoryEditApi(this.editDatas).then((res) => {
        // 重新请求一下list数据
        this.getCategoryListDatas();
        this.$message(res.data.msg);
        this.dialogEditFormVisible = false;
      });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getCategoryListDatas();
    this.getAddCategoryListDatas();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style>
.el-col {
  padding: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>